package com.liuqi.knet.rpc.exchange;

import com.liuqi.knet.remoting.ChannelHandler;
import com.liuqi.knet.remoting.Client;
import com.liuqi.knet.remoting.ClientConfig;
import com.liuqi.knet.remoting.RemotingException;
import com.liuqi.knet.remoting.Server;
import com.liuqi.knet.remoting.ServerConfig;
import com.liuqi.knet.remoting.transport.netty.NettyClient;
import com.liuqi.knet.remoting.transport.netty.NettyServer;
import com.liuqi.knet.rpc.Invoker;
import java.net.InetSocketAddress;

/**
 * 创建服务端和客户端
 *
 * @author liuqi
 * @date 2025/3/6 15:33
 **/
public class Exchangers {

    /**
     * 创建服务端
     *
     * @param bindAddress
     * @param handler
     * @return
     * @throws RemotingException
     */
    public static Server bind(InetSocketAddress bindAddress, ChannelHandler handler, Invoker invoker) throws RemotingException {
        if (bindAddress == null) {
            throw new NullPointerException("bindAddress == null");
        }
        if (handler == null) {
            throw new NullPointerException("handler == null");
        }
        if (invoker == null) {
            throw new NullPointerException("invoker == null");
        }
        return new NettyServer(new ExchangeHandler(handler, invoker), new ServerConfig(bindAddress));
    }

    /**
     * 创建客户端
     *
     * @param remoteAddress
     * @param handler
     * @return
     * @throws RemotingException
     */
    public static Client connect(InetSocketAddress remoteAddress, ChannelHandler handler, Invoker invoker) throws RemotingException {
        if (remoteAddress == null) {
            throw new NullPointerException("remoteAddress == null");
        }
        if (handler == null) {
            throw new NullPointerException("handler == null");
        }
        if (invoker == null) {
            throw new NullPointerException("invoker == null");
        }
        NettyClient client = new NettyClient(new ExchangeHandler(handler, invoker), new ClientConfig(remoteAddress));
        return client;
    }

    /**
     * 客户端重连
     *
     * @param client
     * @throws RemotingException
     */
    public static boolean reconnect(Client client) throws RemotingException {
        if (client == null) {
            throw new NullPointerException("client == null");
        }
        client.reconnect();
        if (client.isConnected()) {
            return true;
        }
        return false;
    }

}
